package org.mfoyou.agent.task.main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * dubbo 启动类
 *
 * @author hzhang7
 */
public class DubboStarter {

    private static Logger logger = LoggerFactory.getLogger(DubboStarter.class);

    public static ApplicationContext ac;

    /**
     * start dubbo
     *
     * @param args
     */
    private static void startDubbo(String[] args) {
        ac = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            private volatile boolean hasShutdown = false;
            private AtomicInteger shutdownTimes = new AtomicInteger(0);

            @Override
            public void run() {
                synchronized (this) {
                    logger.info("shutdown hook was invoked, " + this.shutdownTimes.incrementAndGet());
                    if (!this.hasShutdown) {
                        this.hasShutdown = true;
                        long begineTime = System.currentTimeMillis();
                        long consumingTimeTotal = System.currentTimeMillis() - begineTime;
                        logger.info("shutdown hook over, consuming time total(ms): " + consumingTimeTotal);
                    }
                }
            }
        }, "ShutdownHook"));
        TaskController taskController = ac.getBean("taskController", TaskController.class);
        // 初始化任务
        taskController.init();
    }

    /**
     * 开发环境测试时使用main方法启动 task dubbo, 服务器上部署的时 使用 /bin/start.sh 等启动
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        startDubbo(args);
    }

}
